
package cup.modules.system.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import cup.common.cache.DictCache;
import cup.common.common.MyRoleConstant;
import cup.common.enums.DictEnum;
import cup.core.redis.cache.CupRedis;
import cup.modules.system.entity.Dept;
import cup.modules.system.entity.Role;
import cup.modules.system.service.IRoleService;
import cup.modules.system.vo.DeptVO;
import cup.modules.system.wrapper.DeptWrapper;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import cup.core.boot.ctrl.CupController;
import cup.core.cache.utils.CacheUtil;
import cup.core.launch.constant.AppConstant;
import cup.core.mp.support.Condition;
import cup.core.secure.CupUser;
import cup.core.secure.annotation.PreAuth;
import cup.core.secure.constant.AuthConstant;
import cup.core.tenant.annotation.NonDS;
import cup.core.tool.api.R;
import cup.core.tool.constant.CupConstant;
import cup.core.tool.constant.RoleConstant;
import cup.core.tool.support.Kv;
import cup.core.tool.utils.Func;
import cup.modules.system.service.IDeptService;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static cup.core.cache.constant.CacheConstant.SYS_CACHE;

/**
 * 控制器
 *
 * @author
 */
@NonDS
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_SYSTEM_NAME + "/dept")
@Api(value = "部门", tags = "部门")
//@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
public class DeptController extends CupController {

	private final IDeptService deptService;

	private final IRoleService roleService;

	private final CupRedis cupRedis;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入dept")
	public R<DeptVO> detail(Dept dept) {
		Dept detail = deptService.getOne(Condition.getQueryWrapper(dept));
		return R.data(DeptWrapper.build().entityVO(detail));
	}

	/**
	 * 列表
	 */
	@GetMapping("/list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "deptName", value = "部门名称", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "fullName", value = "部门全称", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "列表", notes = "传入dept")
	public R<List<DeptVO>> list(@ApiIgnore @RequestParam Map<String, Object> dept, CupUser bladeUser) {
		QueryWrapper<Dept> queryWrapper = Condition.getQueryWrapper(dept, Dept.class);
		queryWrapper.orderByAsc("region_id");
		String tenantId = null == bladeUser ? CupConstant.ADMIN_TENANT_ID : bladeUser.getTenantId();
		List<Dept> list = deptService.list((!tenantId.equals(CupConstant.ADMIN_TENANT_ID)) ? queryWrapper.lambda().eq(Dept::getTenantId, bladeUser.getTenantId()) : queryWrapper);
		return R.data(DeptWrapper.build().listNodeVO(list));
	}

	/**
	 * 懒加载列表
	 */
	@GetMapping("/lazy-list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "deptName", value = "部门名称", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "fullName", value = "部门全称", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "懒加载列表", notes = "传入dept")
	public R<List<DeptVO>> lazyList(@ApiIgnore @RequestParam Map<String, Object> dept, Long parentId, CupUser bladeUser) {
		List<DeptVO> list = deptService.lazyList(bladeUser.getTenantId(), parentId, dept);
		return R.data(DeptWrapper.build().listNodeLazyVO(list));
	}

	/**
	 * 懒加载通讯录相关
	 */
	@GetMapping("/lazy-contact-list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "deptName", value = "部门名称", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "fullName", value = "部门全称", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "懒加载通讯录相关", notes = "传入dept")
	public R<List<DeptVO>> lazyContactList(@ApiIgnore @RequestParam Map<String, Object> dept, Long parentId, CupUser bladeUser) {
		List<DeptVO> list = deptService.lazyContactList(bladeUser.getTenantId(), parentId, dept);
		return R.data(DeptWrapper.build().listNodeLazyVO(list));
	}

	/**
	 * 获取部门树形结构
	 */
	@GetMapping("/tree")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "树形结构", notes = "树形结构")
	public R<List<DeptVO>> tree(String tenantId, CupUser bladeUser) {
		List<DeptVO> tree = deptService.tree(Func.toStrWithEmpty(tenantId, bladeUser.getTenantId()));
		return R.data(tree);
	}

	/**
	 * 懒加载获取部门树形结构
	 */
	@GetMapping("/lazy-tree")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "懒加载树形结构", notes = "树形结构")
	public R<List<DeptVO>> lazyTree(String tenantId, Long parentId, CupUser bladeUser) {
		List<DeptVO> tree = deptService.lazyTree(Func.toStrWithEmpty(tenantId, bladeUser.getTenantId()), parentId);
		return R.data(tree);
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入dept")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R submit(@Valid @RequestBody Dept dept) {
		if (deptService.submit(dept)) {
			CacheUtil.clear(SYS_CACHE);
			// 返回懒加载树更新节点所需字段
			Kv kv = Kv.create().set("id", String.valueOf(dept.getId())).set("tenantId", dept.getTenantId())
					  .set("deptCategoryName", DictCache.getValue(DictEnum.ORG_CATEGORY, dept.getDeptCategory()));
			return R.data(kv);
		}
		return R.fail("操作失败");
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "删除", notes = "传入ids")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		cupRedis.del(CacheUtil.formatCacheName(SYS_CACHE, true) + "*");
		cupRedis.del(CacheUtil.formatCacheName(SYS_CACHE, false) + "*");
		return R.status(deptService.removeDept(ids));
	}

	/**
	 * 下拉数据源
	 */
	@PreAuth(AuthConstant.PERMIT_ALL)
	@GetMapping("/select")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "下拉数据源", notes = "传入id集合")
	public R<List<Dept>> select(String deptId) {
		List<Dept> list = deptService.list(Wrappers.<Dept>lambdaQuery().in(Dept::getId, Func.toLongList(deptId)));
		return R.data(list);
	}


	@ApiOperation("获取当前登录人的直属上级分公司（非部门）")
	@GetMapping("/current/parent")
	public R<Dept> currentParent() {
		Dept dept = deptService.currentParent();
		return R.data(dept);
	}

	/**
	* @Description: 值班值守-1
	* @Author: LuanKay
	* @Date: 2022/8/9
	*/
	@GetMapping("/schedule")
	@ApiOperation("值班值守-1")
	public R<DeptVO> schedule() {
		DeptVO deptVO = this.deptService.schedule();
		return R.data(deptVO);
	}

	/**
	* @Description: 值班人员表部门tree结构
	* @Author: LuanKay
	* @Date: 2022/8/18
	*/
	@GetMapping("/dutyTree")
	@ApiOperation(value = "排班树形结构", notes = "排班树形结构")
	public R<List<DeptVO>> dutyTree() {
		CupUser user = super.getUser();
		//1.判断当前帐号是省级or区县级
		boolean isCity = false;
		List<Long> roleIdList = Func.toLongList(user.getRoleId());
		List<Role> roleList = roleService.getBaseMapper().selectList(new QueryWrapper<Role>().in("id", roleIdList));
		if (!CollectionUtils.isEmpty(roleIdList)){
			for (Role role : roleList) {
				if (MyRoleConstant.HAS_ROLE_CITY.contains(role.getRoleAlias())){
					isCity=true;
					break;
				}
			}
		}
		//2.根据角色权限判断返回内容
		List<DeptVO> tree = new ArrayList<>();
		if (isCity){
			tree = deptService.tree(user.getTenantId());
		}else {
			tree = deptService.dutyTree(user.getDeptId());
		}
		return R.data(tree);
	}

}
